package ccm.communicate.file;

import ccm.common.Configurable;
import ccm.common.ReceiveDataEvent;
import ccm.common.ReceiveDataListener;

import javax.swing.*;
import java.io.*;

public class FileSaver implements ReceiveDataListener, Configurable
{
    protected OutputStream outputStream;

    public FileSaver(String fileName) throws FileNotFoundException
    {
        this(new File(fileName));
    }

    public FileSaver(File file) throws FileNotFoundException
    {
        outputStream=new FileOutputStream(file);
    }

    public static byte[] readAll(File file) throws IOException
    {
        byte[] buf=new byte[(int)file.length()];
        FileInputStream in=new FileInputStream(file);
        in.read(buf);
        in.close();
        return buf;
    }

    public void stop()
    {
        try
        {
            if(outputStream!=null)
                outputStream.close();
            outputStream=null;
        }catch(IOException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 接收到数据事件
     *
     * @param event
     */
    public void receiveData(ReceiveDataEvent event)
    {
        if(outputStream!=null)
        {
            try
            {
                outputStream.write(event.getData());
            }catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取配置用的面板
     *
     * @return 配置用的面板
     */
    public JPanel getConfigJPanel()
    {
        return new FileSaverConfigJPanel();
    }

    public void writeExternal(ObjectOutput out) throws IOException
    {

    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
    {

    }
}
